<?php
class CarAction extends Action{
	public function index(){
		$db=M('goods');
		$data=array();
		$field=array('name','sprice','listpic');
		$allprice=0;
		foreach($_SESSION['car'] as $k=>$v){
			$tmp=$db->field($field)->where(array('id'=>$v['gid']))->find();
			$where=array(
				'gid'=>$v['gid'],
				'id'=>array('IN',explode('|',$v['spec']))
				);
			$goods_attr=M('goods_attr');
			$price=$goods_attr->where($where)->sum('price');
			$spec=$goods_attr->where($where)->field(array('value'))->select();
			$gui=array();
			foreach($spec as $key=>$value){
				$gui[$key]=$value['value'];
			}
			$guige=implode('/',$gui);
			$tmp['price']=$tmp['sprice']+$price;
			$tmp['num']=$v['num'];
			$tmp['lid']=$k;
			$tmp['gid']=$v['gid'];
			$_SESSION['car'][$k]['price']=$tmp['price'];
			$_SESSION['car'][$k]['guige']=$guige;
			$tmp['guige']=$guige;
			$data[]=$tmp;
			$allprice+=($tmp['price']*$tmp['num']);
		}
		$allprice=$allprice;
		$_SESSION['allprice']=$allprice;
		/*p($data);
		die;*/
		$this->allprice=$allprice;
		$this->data=$data;
		$this->display();
	}
	//修改购物车
	public function editCar(){
		$lid=intval($_GET['lid']);
		$type=intval($_GET['type']);
		switch($type){
			case 1:
			$_SESSION['car'][$lid]['num']--;
			if($_SESSION['car'][$lid]['num']<=0){
				unset($_SESSION['car'][$lid]);
			}
			if(count($_SESSION['car'])<=0){
				unset($_SESSION['car']);
				unset($_SESSION['allprice']);
				unset($_SESSION['car_count']);
			}
			redirect(U('index'));
			break;
			case 2:
			$_SESSION['car'][$lid]['num']++;
			redirect(U('index'));
			break;
			case 3:
			unset($_SESSION['car'][$lid]);
			if(count($_SESSION['car'])<=0){
				unset($_SESSION['car']);
				unset($_SESSION['allprice']);
				unset($_SESSION['car_count']);
			}
			redirect(U('index'));
			break;
			case 4:
			unset($_SESSION['car']);
			unset($_SESSION['allprice']);
			unset($_SESSION['car_count']);
			redirect(U('index'));
			break;
		}
		
	}
	//检测是否登录
	public function check_login(){
		if(!$this->isAjax()){
			halt('页面不存在');
		}
		if($_SESSION['uid']){
			echo 1;
		}else{
			echo 0;
		}
	}

	//验证码
	public function verify(){
		import('ORG.Util.Image');
		Image::buildImageVerify();
	}
	//验证用户登录
	public function login(){
		if(!$this->isPost()){
			halt('页面不存在');
		}
		if($this->_post('verify','md5')!=$_SESSION['verify']){
			$this->error('验证码错误');
		};
		$name=htmlspecialchars($_POST['username']);
		$pwd=md5($_POST['pwd']);
		$db=M('user');
		$where=array('username'=>$name);
		$user=$db->where($where)->find();
		if(!$user  || $user['password']!=$pwd){
			$this->error('用户名或密码错误');
		}
		/*if($user['lock']){
			$this->error('用户已经被锁定');
		}*/
		$_SESSION['username']=$user['username'];
		$_SESSION['uid']=$user['id'];
		redirect(U('Order/index'));

	}
	
	
	
}
?>